﻿#include <cstdio>

#include "Afterglow.cuh"

//所有的功率减少sub值,以purpose的值做归一化,计算实际y轴对应的索引值
__device__ int normal(float data, int sub, int purpose, int h) {
  return (data - sub) / purpose * h;
}

__global__ void fun(float *d_out, float *d_in, int w, int h, int sub,
                    int purpose) {
  const int column{static_cast<int>(blockDim.x * blockIdx.x + threadIdx.x)};
  const int row{static_cast<int>(blockDim.y * blockIdx.y + threadIdx.y)};
  const int idx{w * row + column};
  if (column >= w || row >= h)
    return;
  if (row == normal(d_in[column], sub, purpose, h)) {
    d_out[idx] = 1;
  } else {
    d_out[idx] = 0;
  }
}

float *d_out;
float *d_in;

void initialize(int w, int h) {
  const unsigned data_size{static_cast<unsigned int>(sizeof(float) * w * h)};
  cudaMalloc(&d_out, data_size);
  cudaMalloc(&d_in, data_size);
}

void myFree() {
  cudaFree(d_out);
  cudaFree(d_in);
}

void foo(float *in, int w, int h, int sub, int purpose, float *out) {
  const unsigned TX{8};
  const unsigned TY{4};
  const unsigned BX{(w - 1) / TX + 1};
  const unsigned BY{(h - 1) / TY + 1};
  const dim3 gridSize{BX, BY};
  const dim3 blockSize{TX, TY};
  const unsigned data_size{static_cast<unsigned int>(sizeof(float) * w * h)};
  cudaMemcpy(d_in, in, data_size, cudaMemcpyHostToDevice);
  fun<<<gridSize, blockSize>>>(d_out, d_in, w, h, sub, purpose);

  cudaMemcpy(out, d_out, data_size, cudaMemcpyDeviceToHost);
}